import { openDB } from 'idb';
import { dbInfo } from './utils';
import type { InternalFileSystemDirectoryHandle } from './fs-helpers';

export const openIDB = async () => {
  const db = await openDB(dbInfo.name, dbInfo.version, {
    upgrade(_db) {
      _db.createObjectStore(dbInfo.tables.filehandles);
    },
  });
  return db;
};

export async function storeDirectoryHandle(directoryHandle: InternalFileSystemDirectoryHandle) {
  const db = await openIDB();
  await db.put(dbInfo.tables.filehandles, directoryHandle, '.smap-stores');
  return await db.get(dbInfo.tables.filehandles, '.smap-stores');
}

export async function getStoredDirectoryHandle(): Promise<InternalFileSystemDirectoryHandle> {
  const db = await openIDB();
  return await db.get(dbInfo.tables.filehandles, '.smap-stores');
}
